package com.intelligent.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.pojo.Warehouse;
import com.intelligent.service.WarehouseService;
import com.intelligent.mapper.WarehouseMapper;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.UUID;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

/**
* @author lenovo
* @description 针对表【warehouse(仓库信息表)】的数据库操作Service实现
* @createDate 2025-08-27 15:58:27
*/
@Service
public class WarehouseServiceImpl extends ServiceImpl<WarehouseMapper, Warehouse>
    implements WarehouseService{

	@Override
	public IPage<Warehouse> pageWarehouse(Page<Warehouse> page,
	                                      String warehouseCode,
	                                      String warehouseName,
	                                      String username,
	                                      Integer status) {
		return this.baseMapper.pageWarehouse(page, warehouseCode, warehouseName, username, status);
	}

	@Override
	public Warehouse getByIdWithUser(String warehouseId) {
		return this.baseMapper.selectByIdWithUser(warehouseId);
	}

	@Override
	public Warehouse addWarehouse(Warehouse warehouse) {
		// 生成仓库编号：WH + 时间戳 + 4位随机数
		String warehouseCode = generateWarehouseCode();
		warehouse.setWarehouseCode(warehouseCode);
		
		// 设置默认状态为启用
		if (warehouse.getStatus() == null) {
			warehouse.setStatus(0);
		}
		
		// 插入数据
		this.baseMapper.insertWarehouse(warehouse);
		
		// 返回添加后的完整信息
		return this.getByIdWithUser(warehouse.getWarehouseId().toString());
	}

	/**
	 * 生成仓库编号：WH + 时间戳 + 4位随机数
	 */
	private String generateWarehouseCode() {
		long timestamp = System.currentTimeMillis();
		int random = (int) (Math.random() * 10000);
		return String.format("WH%d%04d", timestamp, random);
	}

	@Override
	public Warehouse updateWarehouse(Warehouse warehouse) {
		// 检查仓库是否存在
		Warehouse existingWarehouse = this.getById(warehouse.getWarehouseId());
		if (existingWarehouse == null) {
			throw new RuntimeException("仓库不存在");
		}
		
		// 更新仓库信息
		this.baseMapper.updateWarehouse(warehouse);
		
		// 返回更新后的完整信息
		return this.getByIdWithUser(warehouse.getWarehouseId().toString());
	}

	@Override
	public void deleteWarehouse(String warehouseId) {
		// 检查仓库是否存在
		Warehouse existingWarehouse = this.getById(warehouseId);
		if (existingWarehouse == null) {
			throw new RuntimeException("仓库不存在");
		}
		
		// 删除仓库
		int result = this.baseMapper.deleteWarehouse(warehouseId);
		if (result <= 0) {
			throw new RuntimeException("删除失败");
		}
	}

}




